package org.jeecg.talentCooperation.fruit.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.talentCooperation.common.vo.Result;
import org.jeecg.talentCooperation.fruit.entity.Fruit;
import org.jeecg.talentCooperation.fruit.model.FruitCommonResultModel;
import org.jeecg.talentCooperation.fruit.model.FruitResultModel;
import org.jeecg.talentCooperation.fruit.model.ResearchFieldRelatedResultModel;
import org.jeecg.talentCooperation.fruit.service.IFruitResultService;
import org.jeecg.talentCooperation.fruit.service.IFruitService;
import org.jeecg.talentCooperation.talent.model.TalentFruitResultModel;
import org.jeecg.talentCooperation.talent.model.TalentResultModel;
import org.jeecg.talentCooperation.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 人才协作
 * @Author: jeecg-boot
 * @Date:   2023-8-17
 * @Version: V1.0
 */
@Api(tags="人才协作")
@RestController
@RequestMapping("/ndTalent/fruit")
@Slf4j
public class FruitController {
	@Autowired
	private IFruitService fruitService;
	@Autowired
	private IFruitResultService fruitResultService;

	@PostMapping(value = "/getFruitTagByField")
	public Result<?> getFruitTag(@RequestBody FruitResultModel fruitResultModel) {

		List<FruitCommonResultModel> tagList = fruitResultService.getFruitTagByField(fruitResultModel);

		return Result.OK(tagList);
	}

	/**
	 * 获取最多领域的前3个
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getMostOfNumForFieldData")
	public Result<?> getMostFieldDataOfNum(@RequestBody FruitResultModel fruitResultModel) {

		List<FruitCommonResultModel> fieldList = fruitResultService.getMostFieldDataOfNum(fruitResultModel);
        List<String> fieldValueList = fieldList.stream().map(FruitCommonResultModel::getName).collect(Collectors.toList());
		Map resultMap = new HashMap();
        String randomType = fruitResultModel.getRandomType();
        if(("1").equals(randomType)){
			getHotFruit(resultMap, fruitResultModel, fieldValueList);
		}if(("2").equals(randomType)){
			getHyFruit(resultMap, fruitResultModel, fieldValueList);
		}if(("3").equals(randomType)){
			getLwFruit(resultMap, fruitResultModel, fieldValueList);
		}else{
			getHotFruit(resultMap, fruitResultModel, fieldValueList);
			getHyFruit(resultMap, fruitResultModel, fieldValueList);
			getLwFruit(resultMap, fruitResultModel, fieldValueList);
		}
		return Result.OK(resultMap);
	}

	private void getHotFruit(Map map, FruitResultModel fruitResultModel, List<String> fieldValueList){
		//随机3个作者 总和7条
		List<Integer> randomHotList = ToolUtil.getRandomList();
		//最多的3个领域  每个领域成果最多的作者
		List<FruitResultModel> fruitResultModelList = new ArrayList<>();
		List<FruitResultModel> queryAllList = new ArrayList<>();
		if(!CollectionUtils.isEmpty(fieldValueList)){
			for (int i = 0; i < fieldValueList.size(); i++) {
			  fruitResultModel.setFieldValue(fieldValueList.get(i));
			  fruitResultModel.setShowFruitNum(randomHotList.get(i));
			  List<FruitResultModel> queryList = fruitResultService.getAuthorDataOfHotField(fruitResultModel);
				queryAllList.addAll(queryList);
			}
			setResult(fruitResultModelList, queryAllList, randomHotList);
		}
		map.put("hotResult", fruitResultModelList);
	}

	private void getHyFruit(Map map, FruitResultModel fruitResultModel, List<String> fieldValueList){
		//重点会议
		List<Integer> randomHyList = ToolUtil.getRandomList();
		List<FruitResultModel> fruitResultModelList = new ArrayList<>();
		List<FruitResultModel> queryAllList = new ArrayList<>();
		if(!CollectionUtils.isEmpty(fieldValueList)){
			fruitResultModel.setType("4");
			for (int i = 0; i < fieldValueList.size(); i++) {
				fruitResultModel.setFieldValue(fieldValueList.get(i));
				fruitResultModel.setShowFruitNum(randomHyList.get(i));
				List<FruitResultModel> queryList = fruitResultService.getAuthorDataOfTypeField(fruitResultModel);
				queryAllList.addAll(queryList);
			}
			setResult(fruitResultModelList, queryAllList, randomHyList);
		}
		map.put("hyResult", fruitResultModelList);
	}

	private void getLwFruit(Map map, FruitResultModel fruitResultModel, List<String> fieldValueList){

		List<Integer> randomLwList = ToolUtil.getRandomList();
		List<FruitResultModel> fruitResultModelList = new ArrayList<>();
		List<FruitResultModel> queryAllList = new ArrayList<>();
		if(!CollectionUtils.isEmpty(fieldValueList)){
			fruitResultModel.setType("6");
			for (int i = 0; i < fieldValueList.size(); i++) {
				fruitResultModel.setFieldValue(fieldValueList.get(i));
				fruitResultModel.setShowFruitNum(randomLwList.get(i));
				List<FruitResultModel> queryList = fruitResultService.getAuthorDataOfTypeField(fruitResultModel);
				queryAllList.addAll(queryList);
			}
			setResult(fruitResultModelList, queryAllList, randomLwList);
		}
		map.put("lwResult", fruitResultModelList);
	}

	private void setResult(List<FruitResultModel> fruitResultModelList, List<FruitResultModel> queryAllList, List<Integer> randomHotList){
		Map<String, List<FruitResultModel>> frmMap = new HashMap<>();
		if(!CollectionUtils.isEmpty(queryAllList)) {
			queryAllList.forEach(frm ->{
				if(!CollectionUtils.isEmpty(frmMap.get(frm.getAuthorName()))){
					frmMap.get(frm.getAuthorName()).add(frm);
				}else{
					List<FruitResultModel> fm = new ArrayList<>();
					fm.add(frm);
					frmMap.put(frm.getAuthorName(), fm);
				}
			});
		}
		frmMap.forEach((key, value) -> {
			FruitResultModel frt = new FruitResultModel();
			frt.setAuthorName(key);
			frt.setResultModelList(value);
			fruitResultModelList.add(frt);
		});
//		for (int i = 0; i < fruitResultModelList.size(); i++) {
//			// 使用Stream API随机选择记录
//			fruitResultModelList.get(i).setResultModelList(
//					new Random().ints(randomHotList.get(i), 0, fruitResultModelList.get(i).getResultModelList().size())
//							.mapToObj(fruitResultModelList.get(i).getResultModelList()::get).collect(Collectors.toList())
//			);
//		}
	}

	/**
	 * 获取领域相关成果--能源、电力
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getHotFruit")
	public Result<?> getHotFruit(@RequestBody FruitResultModel fruitResultModel) {

		Integer pageNo = fruitResultModel.getPageNo();
		Integer pageSize = fruitResultModel.getPageSize();
//
		fruitResultModel.setPageNo((pageNo - 1) * pageSize);
		fruitResultModel.setPageSize(pageSize);
		Page<FruitResultModel> pageList = new Page<FruitResultModel>(pageNo, pageSize);
		pageList = fruitResultService.getHotFruit(pageList, fruitResultModel);

		return Result.OK(pageList);
	}

	/**
	 * 获取领域相关成果
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getFieldLinkFruit")
	public Result<?> getFieldLinkFruit(@RequestBody FruitResultModel fruitResultModel) {

		Integer pageNo = fruitResultModel.getPageNo();
		Integer pageSize = fruitResultModel.getPageSize();
//
		fruitResultModel.setPageNo((pageNo - 1) * pageSize);
		fruitResultModel.setPageSize(pageSize);
		Page<FruitResultModel> pageList = new Page<FruitResultModel>(pageNo, pageSize);
		pageList = fruitResultService.getFieldLinkFruit(pageList, fruitResultModel);

		return Result.OK(pageList);
	}

	/**
	 * 分页列表查询
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/list")
	public Result<?> queryPageList(@RequestBody FruitResultModel fruitResultModel) {

		Integer pageNo = fruitResultModel.getPageNo();
		Integer pageSize = fruitResultModel.getPageSize();
		Result<IPage<FruitResultModel>> result = new Result<IPage<FruitResultModel>>();

		fruitResultModel.setPageNo((pageNo - 1) * pageSize);
		fruitResultModel.setPageSize(pageSize);
		Page<FruitResultModel> pageList = new Page<FruitResultModel>(pageNo, pageSize);
		pageList = fruitResultService.getFruitListOfPage(pageList, fruitResultModel);
		result.setResult(pageList);
		result.setSuccess(true);

		return Result.OK(pageList);
	}


	/**
	 * 专家数据
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getTalentData")
	public Result<?> getTalentData(@RequestBody FruitResultModel fruitResultModel) {

		Integer pageNo = fruitResultModel.getPageNo();
		Integer pageSize = fruitResultModel.getPageSize();

		fruitResultModel.setPageNo((pageNo - 1) * pageSize);
		fruitResultModel.setPageSize(pageSize);
		Page<TalentFruitResultModel> talentFruitPageList = new Page<TalentFruitResultModel>(pageNo, pageSize);
//		talentFruitPageList = fruitResultService.getTalentGroupDataBySearchContentOfPage(talentFruitPageList, fruitResultModel);
		//新逻辑
		talentFruitPageList = fruitResultService.getTalentDataBySearchContent(talentFruitPageList, fruitResultModel);

		return Result.OK(talentFruitPageList);
	}

	/**
	 * 专家领域数据
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getTalentFieldData")
	public Result<?> getTalentFieldData(@RequestBody FruitResultModel fruitResultModel) {

//		Map map = new HashMap();
//
//		Integer pageNo = fruitResultModel.getPageNo();
//		Integer pageSize = fruitResultModel.getPageSize();
//
//		fruitResultModel.setPageNo((pageNo - 1) * pageSize);
//		fruitResultModel.setPageSize(pageSize);
//		fruitResultService.setModelFruitIdList(fruitResultModel);

//		//获取研究领域
//		Page<FruitCommonResultModel> talentFieldPageList = new Page<FruitCommonResultModel>(pageNo, pageSize);
//		talentFieldPageList = fruitResultService.getFruitFieldGroupCount(talentFieldPageList, fruitResultModel);

		return Result.OK(fruitResultService.getFruitFieldGroupCount(fruitResultModel));
	}

	/**
	 * 专家合作部门数据
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getTalentDeptData")
	public Result<?> getTalentDeptData(@RequestBody FruitResultModel fruitResultModel) {

		Integer pageNo = fruitResultModel.getPageNo();
		Integer pageSize = fruitResultModel.getPageSize();

		fruitResultModel.setPageNo((pageNo - 1) * pageSize);
		fruitResultModel.setPageSize(pageSize);
		Page<FruitCommonResultModel> talentFruitDeptPageList = new Page<FruitCommonResultModel>(pageNo, pageSize);

		talentFruitDeptPageList = fruitResultService.getFruitDeptGroupCount(talentFruitDeptPageList, fruitResultModel);

		return Result.OK(talentFruitDeptPageList);
	}


	/**
	 * 专家个人研究领域
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getTalentFieldTagData")
	public Result<?> getTalentFieldTagData(@RequestBody FruitResultModel fruitResultModel) {

		List<FruitCommonResultModel> fieldData = fruitResultService.getTalentFieldTagData(fruitResultModel);

//		LinkedHashMap map = new LinkedHashMap();
//		fieldData.forEach(frm -> {
//			String mapKey = frm.getField();
//			if (frm.getField().contains(";")) {
//				String[] fieldArr = frm.getField().split(";");
//				for (String s : fieldArr) {
//					mapKey = s ;
//					map.putIfAbsent(mapKey, frm);
//				}
//			}else{
//				map.putIfAbsent(mapKey, frm);
//			}
//		});
		return Result.OK(fieldData);
	}

	/**
	 * 研究领域关联
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getRelatedResearchFieldChart")
	public Result<?> getRelatedResearchFieldChart(@RequestBody FruitResultModel fruitResultModel) {

		List<FruitResultModel> fieldData = fruitResultService.getResearchFieldData(fruitResultModel);
		Map<String, Integer> mapNodeName = new HashMap();
		Map<String, String> mapNode = new HashMap();
		Set<String> fieldNameList = new HashSet<>();
		if(!CollectionUtils.isEmpty(fieldData)){
			//该专家所有领域
			fieldData.forEach(
					frm -> {
						String startNode = frm.getId();
						String startNodeName = frm.getField();
						int crossTimes = frm.getCount();
//						mapNodeName.putIfAbsent(startNodeName, crossTimes);
//						mapNode.putIfAbsent(startNodeName, startNode);
						if (startNodeName.contains(";")) {
							String[] fieldNameArr = frm.getField().split(";");
							for (String fieldName : fieldNameArr) {
								if(mapNodeName.get(fieldName) != null){
									mapNodeName.merge(fieldName, crossTimes, Integer::sum);
								}else{
									fieldNameList.add(fieldName);
									mapNode.putIfAbsent(fieldName, startNode);
									mapNodeName.putIfAbsent(fieldName, crossTimes);
								}
							}
						}else{
							fieldNameList.add(startNodeName);
							mapNode.putIfAbsent(startNodeName, startNode);
							mapNodeName.putIfAbsent(startNodeName, crossTimes);
						}
					});

			//互相之间连线  两两组合
//			List<Pair<String, String>> pairs = combineTwoElement(new ArrayList<>(fieldNameList));
			Map<String, String> pairsMap = arrayCombinations(fieldNameList.toArray());

			List<ResearchFieldRelatedResultModel> rfrmList = new ArrayList<>();
			pairsMap.forEach((key, value) -> {
				ResearchFieldRelatedResultModel rfrm = new ResearchFieldRelatedResultModel();
				rfrm.setStart_node_name(key);
				rfrm.setStart_node(mapNode.get(key));
				rfrm.setCross_times(mapNodeName.get(key));
				rfrm.setEnd_node(mapNode.get(value));
				rfrm.setEnd_node_name(value);
				rfrmList.add(rfrm);
			});
			return Result.OK(rfrmList);
		}
		return null;
	}

	/**
	 * 研究领域关联--饼状图
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getRelatedResearchFieldPieChart")
	public Result<?> getRelatedResearchFieldPieChart(@RequestBody FruitResultModel fruitResultModel) {

		List<FruitResultModel> fieldData = fruitResultService.getResearchFieldData(fruitResultModel);

		return Result.OK(fieldData);
	}

//	public static List<Pair<String, String>> combineTwoElement(List<String> list) {
//		List<Pair<String, String>> resultList = Lists.newArrayListWithExpectedSize(list.size()*list.size()/2);
//		if (CollectionUtils.isEmpty(list)) {
//			return null;
//		}
//		if (list.size() >= 2) {
//			for (int j = 0; j < list.size(); j++) {
//				resultList.addAll(ll(list.subList(j,list.size())));
//			}
//		}
//		return resultList;
//	}
//
//
//	public static List<Pair<String, String>> ll (List<String> list){
//		List<Pair<String, String>> resultList = Lists.newArrayListWithExpectedSize(list.size()*list.size()/2);
//
//		for (int j = 1; j < list.size(); j++) {
//			resultList.add(new Pair<>(list.get(0), list.get(j)));
//		}
//		return  resultList;
//	}

	public Map<String, String> arrayCombinations (Object[] arr){
		Map<String, String> map = new HashMap<>();
		// 使用嵌套循环遍历数组
		for (int i = 0; i < arr.length; i++) {
			for (int j = i + 1; j < arr.length; j++) {
				map.putIfAbsent(arr[i] + "", arr[j] + "");
			}
		}
		return map;
	}
	
	/**
	 * 成果统计
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getFruitChart")
	public Result<?> getFruitChart(@RequestBody FruitResultModel fruitResultModel) {

		Result<List<FruitResultModel>> result = new Result<List<FruitResultModel>>();

		List<FruitResultModel> resultModelList = fruitResultService.getFruitChart(fruitResultModel);

		result.setResult(resultModelList);
		result.setSuccess(true);

		return Result.OK(result);
	}

	/**
	 * 成果词云
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getFruitWordCloud")
	public Result<?> getFruitWordCloud(@RequestBody FruitResultModel fruitResultModel) {

		Result<List<FruitResultModel>> result = new Result<List<FruitResultModel>>();

		List<FruitResultModel> resultModelList = fruitResultService.getFruitWordCloud(fruitResultModel);

		result.setResult(resultModelList);
		result.setSuccess(true);

		return Result.OK(result);
	}

	/**
	 * 相关作者
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getRelatedTalentChart")
	public Result<?> getRelatedTalentChart(@RequestBody FruitResultModel fruitResultModel) {

		Result<List<TalentResultModel>> result = new Result<List<TalentResultModel>>();

		List<TalentResultModel> resultModelList = fruitResultService.getRelatedTalentChart(fruitResultModel);

		result.setResult(resultModelList);
		result.setSuccess(true);

		return Result.OK(result);
	}

	/**
	 * 相关 推荐专家
	 *
	 * @param fruitResultModel
	 * @return
	 */
	@PostMapping(value = "/getRecommendTalent")
	public Result<?> getRecommendTalent(@RequestBody FruitResultModel fruitResultModel) {

		Result<List<FruitResultModel>> result = new Result<>();

		List<FruitResultModel> resultModelList = new ArrayList<>();

		String[] filedNameArr = fruitResultModel.getFieldNames();
		if(filedNameArr!= null && filedNameArr.length > 0){
			for (String fieldName : filedNameArr) {
				FruitResultModel frm = new FruitResultModel();
				frm.setField(fieldName);
				frm.setOrgUserId(fruitResultModel.getOrgUserId());
				List<FruitResultModel> list = fruitResultService.getRecommendTalent(frm);
				frm.setFieldNames(list.stream().map(item -> item.getAuthorName() + "," + item.getOrgUserId()).distinct().toArray(String[]::new));

				Map<String, FruitResultModel> map = new HashMap();
                for (FruitResultModel ff : list) {
                    map.putIfAbsent(ff.getFruitName(), ff);
                }
				frm.setResultModelList(new ArrayList<>(map.values()));
				resultModelList.add(frm);
			}
		}
		result.setResult(resultModelList);
		result.setSuccess(true);

		return Result.OK(result);
	}


}
